<template>
	<view class="container">
		<form @submit="submitForm" class="form-container">
			<!-- 申请人公司姓名 -->
			<view class="form-item">
				<view class="form-label">申请人公司姓名
					<text class="required">*</text>
				</view>
				<view class="form-content">
					<input v-model="form.sqrComName" placeholder="请输入申请人公司姓名" class="input-control" />
				</view>
				<view class="error-message" v-if="errors.sqrComName">{{ errors.sqrComName }}</view>
			</view>

			<!-- 受益人公司姓名 -->
			<view class="form-item">
				<view class="form-label">受益人公司姓名
					<text class="required">*</text>
				</view>
				<view class="form-content">
					<input v-model="form.syrComName" placeholder="请输入受益人公司姓名" class="input-control" />
				</view>
				<view class="error-message" v-if="errors.syrComName">{{ errors.syrComName }}</view>
			</view>

			<!-- 项目名称 -->
			<view class="form-item">
				<view class="form-label">项目名称<text class="required">*</text></view>
				<view class="form-content">
					<input v-model="form.projectName" placeholder="请输入项目名称" class="input-control" />
				</view>
				<view class="error-message" v-if="errors.projectName">{{ errors.projectName }}</view>
			</view>

			<view class="form-item">
				<view class="form-label">联系人 <text class="required">*</text></view>
				<view class="form-content">
					<input v-model="form.linkPerson" placeholder="请输入联系人" class="input-control" />
				</view>
				<view class="error-message" v-if="errors.linkPerson">{{ errors.linkPerson }}</view>
			</view>

			<!-- 开函人联系方式 -->
			<view class="form-item">
				<view class="form-label">联系方式 <text class="required">*</text></view>
				<view class="form-content">
					<input v-model="form.ksrLinkFs" placeholder="请输入联系方式" class="input-control" />
				</view>
				<view class="error-message" v-if="errors.ksrLinkFs">{{ errors.ksrLinkFs }}</view>
			</view>

			<!-- 单位性质 -->
			<!-- 		<view class="form-item">
				<view class="form-label">单位性质<text class="required">*</text></view>
				<view class="form-content">
					<input v-model="form.dwXz" placeholder="请输入单位性质" class="input-control" />
				</view>
				<view class="error-message" v-if="errors.dwXz">{{ errors.dwXz }}</view>
			</view> -->

			<!-- 单位最高资质-->
			<!-- 		<view class="form-item">
				<view class="form-label">单位最高资质<text class="required">*</text></view>
				<view class="form-content">
					<input v-model="form.dwZz" placeholder="请输入单位最高资质" class="input-control" />
				</view>
				<view class="error-message" v-if="errors.dwZz">{{ errors.dwZz }}</view>
			</view> -->



			<!-- 保函金额 -->
			<view class="form-item">
				<view class="form-label">保函金额(万)<text class="required">*</text></view>
				<view class="form-content">
					<input v-model="form.bhJe" placeholder="请输入保函金额(万)" class="input-control" type="number" />
				</view>
				<view class="error-message" v-if="errors.bhJe">{{ errors.bhJe }}</view>
			</view>

			<!-- 保函期限 -->
			<view class="form-item">
				<view class="form-label">保函期限<text class="required">*</text></view>
				<view class="form-content">
					<uni-data-select v-model="form.bhQx" :localdata="bhQxOptions"></uni-data-select>
				</view>
				<view class="error-message" v-if="errors.bhQx">{{ errors.bhQx }}</view>
			</view>
			<!-- 保函类型 -->
			<view class="form-item">
				<view class="form-label">保函类型</view>
				<view class="form-content">
					<uni-data-select v-model="form.bhType" :localdata="bhTypeOptions"></uni-data-select>
				</view>
				<view class="error-message" v-if="errors.bhType">{{ errors.bhType }}</view>
			</view>

			<!-- 出函要求 -->
			<!-- 		<view class="form-item">
				<view class="form-label">出函要求<text class="required">*</text></view>
				<view class="form-content">
					<textarea v-model="form.chYq" placeholder="请输入出函要求" class="textarea-control"></textarea>
				</view>
				<view class="error-message" v-if="errors.chYq">{{ errors.chYq }}</view>
			</view> -->


			<view class="xmzl">
				项目资料
			</view>


			<!-- 合作合同 -->
			<view class="form-item2">
				<view class="form-label2">
					<view>
						合作合同
					</view>
					<view @click="chooseFile('htFj')">
						<image style="width: 30px;height: 30px;" src="@/static/jia.png" mode=""></image>
					</view>
				</view>
				<view class="form-content">
					<!-- <button class="upload-btn" @click="chooseFile('htFj')">
						选择文件
					</button> -->
					<view class="file-list" v-if="form.htFj.length > 0">
						<view v-for="(file, index) in form.htFj" :key="index" class="file-item">
							<text class="file-name">{{ file.name || file }}</text>
							<text class="delete-icon" @click="removeFile('htFj', index)">×</text>
						</view>
					</view>
				</view>
				<view class="error-message" v-if="errors.htFj">{{ errors.htFj }}</view>
			</view>

			<!-- 招标文件 -->
			<view class="form-item2">
				<view class="form-label2">
					<view>
						招标文件
					</view>
					<view @click="chooseFile('zbwjFj')">
						<image style="width: 30px;height: 30px;" src="@/static/jia.png" mode=""></image>
					</view>
				</view>
				<view class="form-content">
					<view class="file-list" v-if="form.zbwjFj.length > 0">
						<view v-for="(file, index) in form.zbwjFj" :key="index" class="file-item">
							<text class="file-name">{{ file.name || file }}</text>
							<text class="delete-icon" @click="removeFile('zbwjFj', index)">×</text>
						</view>
					</view>
				</view>
				<view class="error-message" v-if="errors.zbwjFj">{{ errors.zbwjFj }}</view>
			</view>

			<!-- 中标通知书 -->
			<view class="form-item2">
				<view class="form-label2">
					<view>
						中标通知书
					</view>
					<view @click="chooseFile('zbtzFj')">
						<image style="width: 30px;height: 30px;" src="@/static/jia.png" mode=""></image>
					</view>

				</view>
				<view class="form-content">
					<!-- 		<button class="upload-btn" @click="chooseFile('zbtzFj')">
						选择文件
					</button> -->
					<view class="file-list" v-if="form.zbtzFj.length > 0">
						<view v-for="(file, index) in form.zbtzFj" :key="index" class="file-item">
							<text class="file-name">{{ file.name || file }}</text>
							<text class="delete-icon" @click="removeFile('zbtzFj', index)">×</text>
						</view>
					</view>
				</view>
				<view class="error-message" v-if="errors.zbtzFj">{{ errors.zbtzFj }}</view>
			</view>

			<!-- 涉诉情况 -->
			<view class="form-item" style="margin-top: 20px;">
				<view class="form-label">涉诉情况</view>
				<view class="form-content">
					<textarea v-model="form.ssqk" placeholder="如有大额失信/被执行，请说明" class="textarea-control"></textarea>
				</view>
			</view>

			<!-- 反担保措施 -->
			<!-- 		<view class="form-item">
				<view class="form-label">反担保措施</view>
				<view class="form-content">
					<textarea v-model="form.fdbCs" placeholder="请输入内容" class="textarea-control"></textarea>
				</view>
			</view> -->



			<!-- 按钮区域 -->
			<view class="button-group">
				<button type="primary" form-type="submit" class="submit-btn">确定</button>
				<!-- 				<button type="default" @click="cancel" class="cancel-btn">取消</button> -->
			</view>
		</form>

	</view>
</template>

<script>
	import {
		addXx,
		getDict
	} from '@/api/business/index.js'
	import {
		request
	} from '@/utils/request.js'
	import config from '@/config'

	export default {
		name: 'GuaranteeForm',
		onLoad(options) {
			this.form.userId = options.userId || '';
			this.form.parentUserId = options.parentUserId || '';
			this.getDictInt()
		},
		data() {
			return {
				form: {
					sqrComName: '',
					syrComName: '',
					projectName: '',
					dwXz: '',
					dwZz: '',
					bhType: '',
					bhJe: '',
					bhQx: '',
					chYq: '',
					htFj: [], // 改为数组
					zbwjFj: [], // 改为数组
					zbtzFj: [], // 改为数组
					ssqk: '',
					fdbCs: '',
					ksrLinkFs: '',
					userId: '',
					parentUserId: ''
				},
				errors: {
					sqrComName: '',
					syrComName: '',
					projectName: '',
					dwXz: '',
					dwZz: '',
					bhType: '',
					bhJe: '',
					bhQx: '',
					chYq: '',
					htFj: '',
					zbwjFj: '',
					zbtzFj: '',
					ksrLinkFs: '',
					linkPerson: '',
				},
				bhTypeOptions: [],
				bhQxOptions: [],
				bhTypeIndex: null,
				bhQxIndex: null
			}
		},
		methods: {
			getDictInt() {
				getDict("bhqx").then(res => {
					if (res.code === 200) {
						for (let i = 0; i < res.data.length; i++) {
							// i：当前索引，数组[i]：当前元素
							const ll = {
								value: res.data[i].dictValue,
								text: res.data[i].dictLabel
							}
							this.bhQxOptions.push(ll)
						}
					}
				})
				this.bhTypeOptions = []
				getDict("bh_type").then(res => {
					if (res.code === 200) {
						console.log(res.data, "9999")
						for (let i = 0; i < res.data.length; i++) {
							// i：当前索引，数组[i]：当前元素
							const ll = {
								value: res.data[i].dictValue,
								text: res.data[i].dictLabel
							}
							this.bhTypeOptions.push(ll)
						}
					}
				})
			},
			handleBhTypeChange(e) {
				const index = e.detail.value;
				this.form.bhType = this.bhTypeOptions[index];
			},
			handleBhQxChange(e) {
				const index = e.detail.value;
				this.form.bhQx = this.bhQxOptions[index];
			},
			validateForm() {
				let isValid = true;
				const newErrors = JSON.parse(JSON.stringify(this.errors));

				Object.keys(newErrors).forEach(key => {
					newErrors[key] = '';
				});

				if (!this.form.sqrComName) {
					newErrors.sqrComName = '请输入申请人公司姓名';
					isValid = false;
				}
				if (!this.form.syrComName) {
					newErrors.syrComName = '请输入受益人公司姓名';
					isValid = false;
				}
				if (!this.form.projectName) {
					newErrors.projectName = '请输入项目名称';
					isValid = false;
				}
				if (!this.form.linkPerson) {
					newErrors.linkPerson = '请输入联系人';
					isValid = false;
				}
				if (!this.form.ksrLinkFs) {
					newErrors.ksrLinkFs = '请输入联系方式';
					isValid = false;
				}
				if (!this.form.bhJe) {
					newErrors.bhJe = '请输入保函金额';
					isValid = false;
				} else if (isNaN(Number(this.form.bhJe)) || Number(this.form.bhJe) <= 0) {
					newErrors.bhJe = '请输入有效的保函金额';
					isValid = false;
				}
				if (!this.form.bhQx) {
					newErrors.bhQx = '请选择保函期限';
					isValid = false;
				}
				// if (!this.form.htFj || this.form.htFj.length === 0) {
				// 	newErrors.htFj = '请选择合作合同文件';
				// 	isValid = false;
				// }


				this.errors = newErrors;
				return isValid;
			},
			submitForm(e) {
				e.preventDefault();
				if (this.validateForm()) {
					// 构造提交数据
					const submitData = {
						...this.form
					};
					submitData.htFj = this.form.htFj.map(file => file.fileName).join(',');
					submitData.zbwjFj = this.form.zbwjFj.map(file => file.fileName).join(',');
					submitData.zbtzFj = this.form.zbtzFj.map(file => file.fileName).join(',');

					addXx(submitData)
						.then(res => {
							if (res.code === 200) {
								uni.showToast({
									title: '提交成功',
									icon: 'success',
									duration: 1000
								});
								this.resetForm();
								//this.cancel();
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none',
									duration: 2000
								});
							}
						})
						.catch(err => {
							console.error('接口调用失败:', err);
							console.error('接口调用失败:', err.data.msg);
							uni.showToast({
								title: err.data.msg,
								icon: 'none',
								duration: 2000
							});
						});
				} else {
					uni.showToast({
						title: '请完善必填项',
						icon: 'none',
						duration: 2000
					});
				}
			},
			// 重置表单方法，保留 userId 和 parentUserId
			resetForm() {
				// 保存 userId 和 parentUserId
				const userId = this.form.userId;
				const parentUserId = this.form.parentUserId;

				// 重置表单数据
				this.form = {
					sqrComName: '',
					syrComName: '',
					projectName: '',
					dwXz: '',
					dwZz: '',
					bhType: '',
					bhJe: '',
					bhQx: '',
					chYq: '',
					htFj: [],
					zbwjFj: [],
					zbtzFj: [],
					ssqk: '',
					fdbCs: '',
					ksrLinkFs: '',
					userId: userId,
					parentUserId: parentUserId
				};

				// 重置错误信息
				Object.keys(this.errors).forEach(key => {
					this.errors[key] = '';
				});
			},
			cancel() {
				uni.navigateBack();
			},
			async chooseFile(field) {
				uni.chooseFile({
					count: 10, // 允许选择多个文件
					success: async (res) => {
						// 将选择的文件添加到对应字段的数组中
						const files = [];
						res.tempFiles.forEach(file => {
							files.push({
								name: file.name,
								path: file.path,
								size: file.size
							});
						});

						// 将文件添加到表单中
						this.form[field].push(...files);
						console.log(`选择了${field}文件:`, res.tempFiles);

						// 立即上传文件
						for (let i = this.form[field].length - files.length; i < this.form[field]
							.length; i++) {
							try {
								await this.uploadSingleFile(field, i);
							} catch (err) {
								console.error(`文件上传失败:`, err);
								uni.showToast({
									title: '文件上传失败',
									icon: 'none',
									duration: 2000
								});
							}
						}
					}
				});
			},
			removeFile(field, index) {
				// 删除指定索引的文件
				this.form[field].splice(index, 1);
			},
			// 上传单个文件
			uploadSingleFile(field, index) {
				return new Promise((resolve, reject) => {
					const file = this.form[field][index];

					// 标记文件为上传中状态
					this.$set(this.form[field][index], 'uploading', true);
					this.$set(this.form[field][index], 'uploadError', '');

					// 使用 UniApp 原生上传 API（替代自定义 request）
					uni.uploadFile({
						url: config.baseUrl + '/common/nologin/uploadFile', // 后端上传接口地址（若需要完整URL可拼接baseUrl）
						filePath: file.path, // 本地文件临时路径（UniApp要求的参数）
						name: 'file', // 后端接收文件的参数名（需与后端一致）
						header: {
							// 如需登录态可添加token（根据实际需求）
							// 'Authorization': uni.getStorageSync('token')
						},
						// 额外参数（如果后端需要其他表单数据）
						formData: {
							// 例如：fileType: field  // 可区分不同类型的文件
						},
						success: (uploadRes) => {
							// 解析后端返回的JSON数据（注意：uploadRes.data是字符串需转换）
							let res;
							try {
								res = JSON.parse(uploadRes.data);
							} catch (e) {
								this.$set(this.form[field][index], 'uploading', false);
								this.$set(this.form[field][index], 'uploadError', '解析返回数据失败');
								return reject(new Error('解析返回数据失败'));
							}

							if (res.code === 200 && res.fileName) {
								// 上传成功：保存后端返回的文件名，清除上传状态
								this.$set(this.form[field][index], 'fileName', res.fileName);
								this.$set(this.form[field][index], 'uploading', false);
								resolve(res.fileName);
							} else {
								// 上传失败：记录错误信息
								this.$set(this.form[field][index], 'uploading', false);
								this.$set(this.form[field][index], 'uploadError', res.msg || '文件上传失败');
								reject(new Error(res.msg || '文件上传失败'));
							}
						},
						fail: (err) => {
							// 网络错误处理
							this.$set(this.form[field][index], 'uploading', false);
							this.$set(this.form[field][index], 'uploadError', '网络异常，上传失败');
							reject(new Error(`网络错误: ${err.errMsg}`));
						}
					});
				});
			}

		}
	}
</script>

<style scoped>
	.file-list {
		margin-top: 10px;
	}

	.file-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 5px 0;
		border-bottom: 1px solid #eee;
	}

	.file-name {
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.delete-icon {
		color: #ff4d4f;
		font-size: 20px;
		font-weight: bold;
		padding: 0 10px;
		cursor: pointer;
	}

	.container {
		padding: 16px;
		padding-top: 0px;
		background-color: white;
		min-height: 100vh;
	}

	.form-container {
		background-color: #fff;
		border-radius: 8px;
		padding: 20px 16px;
	}

	.form-item {
		display: flex;
		flex-direction: column;
		margin-bottom: 20px;
	}

	.form-item2 {
		display: flex;
		flex-direction: column;
	}

	.form-label {
		font-size: 14px;
		color: #333;
		margin-bottom: 8px;
		width: 100%;
		box-sizing: border-box;
	}

	.form-label2 {
		font-size: 14px;
		color: #333;
		width: 100%;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 50px;
		border-bottom: 1px solid #F6F6F6;
		padding-left: 5px;
	}

	.form-content {
		width: 100%;
	}

	.input-control {
		width: 100%;
		height: 44px;
		padding: 0 12px;
		border: 1px solid #ddd;
		border-radius: 4px;
		font-size: 14px;
		box-sizing: border-box;
	}

	.textarea-control {
		width: 100%;
		min-height: 100px;
		padding: 12px;
		border: 1px solid #ddd;
		border-radius: 4px;
		font-size: 14px;
		box-sizing: border-box;
		resize: vertical;
	}

	.picker-display {
		width: 100%;
		height: 44px;
		line-height: 44px;
		padding: 0 12px;
		border: 1px solid #ddd;
		border-radius: 4px;
		font-size: 14px;
		color: #666;
		box-sizing: border-box;
	}

	.upload-btn {
		width: 100%;
		height: 44px;
		line-height: 44px;
		text-align: center;
		border: 1px dashed #ddd;
		border-radius: 4px;
		font-size: 14px;
		color: #666;
		background-color: #f9f9f9;
		padding: 0;
	}

	.xmzl {
		background-color: #F6F6F6;
		height: 44px;
		line-height: 44px;
		padding-left: 5px;
		font-weight: bolder;
		font-size: 14px;
	}

	.error-message {
		margin-top: 4px;
		font-size: 12px;
		color: #ff4d4f;
	}

	.button-group {
		display: flex;
		justify-content: center;
		gap: 16px;
		margin-top: 30px;
	}

	.submit-btn,
	.cancel-btn {
		width: 120px;
		height: 44px;
		line-height: 44px;
		border-radius: 4px;
		font-size: 16px;
		padding: 0;
	}

	.submit-btn {
		background-color: #007aff;
		color: #fff;
		border: none;
	}

	.cancel-btn {
		background-color: #fff;
		color: #333;
		border: 1px solid #ddd;
	}

	.required {
		color: red;
		margin-left: 4px;
	}

	@media (min-width: 768px) {
		.form-item {
			flex-direction: row;
			align-items: center;
		}

		.form-label {
			width: 120px;
			margin-bottom: 0;
			text-align: right;
			padding-right: 16px;
		}

		.form-content {
			flex: 1;
		}
	}
</style>